import axios from "axios";
import { user } from "@stores/user";
import { config } from "@config/index";
import { server } from "./abort";

const globalOptions = {
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
    Authorization: user.getToken(),
  },
};


export type Res = {
  code: number;
  data: any;
  message: string;
}

export type Method = 'get' | 'post' | 'delete' | 'put'

export default class BasicService {
  baseURL: string;

  constructor(baseURL = "") {
    this.baseURL = baseURL;
  }

  _setRqHeaderToken(token: string) {
    user.setToken(token);
    globalOptions.headers.Authorization = token;
  }

  get(url: string, options?: any) {
    return this._request("get", url, null, options);
  }

  post(url: string, data?: any, options?: any) {
    return this._request("post", url, data, options);
  }

  put(url: string, data?: any, options?: any) {
    return this._request("put", url, data, options);
  }

  delete(url: string, options?: any) {
    return this._request("delete", url, {}, options);
  }

  abort(url: string) {
    if (url) {
      server.abort(url);
    } else {
      console.warn("abort必须传入url参数");
    }
  }

  abortAll() {
    server.abortAll();
  }

  _request(method: Method, url: string, data: any, options: any = {}) {
    const headers = Object.assign({}, globalOptions.headers, options.headers);
    const opt = {
      baseURL: this.baseURL,
      withCredentials: true,
      method,
      url: /https?:\/\//.test(url) ? url : config.apiHost + url,
      data,
      // params: Object.assign(options.params || {}, {
      //   locale: language.getLanguage(),
      // }),
      cancelToken: new axios.CancelToken((cancel) => {
        server.add(url, cancel);
      }),
      headers,
    };
    // axios.defaults.withCredentials = true;

    return axios(opt)
      .then((res: any) => {
        res = res.data as Res;
        // 成功后移除abort
        server.remove(url);
        if (res.code === 1001) {
          console.error("登录失效，请刷新页面重新登录");
          user.clearUserInfo();
          // _window.RouterHistory.push('/');
          return [null, "登录失效"];
        }
        if (res.error) {
          console.log("res.error", res.error);
          return [null, res.error.error_code.message];
        }
        if (res.code !== 0) {
          return [null, res.message];
        } else {
          return [res.data || res, null];
        }
      })
      .catch((err) => {
        if (err?.__CANCEL__) {
          return err;
        }
        console.error("err", err);
        return Promise.reject(err);
      });
  }
}
